import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { authApi, authUtils } from '@/services/authApi'
import { ElMessage } from 'element-plus'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const user = ref(null)
  const token = ref(null)
  const isLoading = ref(false)
  const isInitialized = ref(false)
  const isDarkMode = ref(false)

  // 计算属性
  const isLoggedIn = computed(() => {
    return !!token.value && !!user.value
  })

  const userInfo = computed(() => {
    return user.value || {}
  })

  const isAdmin = computed(() => {
    return user.value?.role === 'ADMIN'
  })

  // 初始化认证状态
  const initAuth = () => {
    if (isInitialized.value) return

    const storedToken = authUtils.getToken()
    const storedUser = authUtils.getUser()

    if (storedToken && storedUser && !authUtils.isTokenExpired()) {
      token.value = storedToken
      user.value = storedUser
    } else {
      // token过期或不存在，清除数据
      authUtils.clearAuthData()
    }

    isInitialized.value = true
  }

  // 初始化主题
  const initTheme = () => {
    const savedTheme = localStorage.getItem('theme')
    // 默认使用黑暗模式
    if (savedTheme === 'light') {
      isDarkMode.value = false
      applyLightMode()
    } else {
      // 默认为黑暗模式
      isDarkMode.value = true
      applyDarkMode()
      localStorage.setItem('theme', 'dark')
    }
  }

  // 切换黑暗模式
  const toggleDarkMode = () => {
    isDarkMode.value = !isDarkMode.value
    if (isDarkMode.value) {
      applyDarkMode()
      localStorage.setItem('theme', 'dark')
    } else {
      applyLightMode()
      localStorage.setItem('theme', 'light')
    }
  }

  // 应用黑暗模式样式
  const applyDarkMode = () => {
    document.documentElement.classList.add('dark')
    document.documentElement.style.colorScheme = 'dark'
  }

  // 应用浅色模式样式
  const applyLightMode = () => {
    document.documentElement.classList.remove('dark')
    document.documentElement.style.colorScheme = 'light'
  }

  // 登录
  const login = async (username, password) => {
    try {
      isLoading.value = true
      
      const response = await authApi.login(username, password)
      
      if (!response || !response.token) {
        throw new Error('登录响应数据格式错误')
      }

      // 保存认证信息
      token.value = response.token
      user.value = response.user
      authUtils.saveAuthData(response.token, response.user)

      ElMessage.success('登录成功')
      return response

    } catch (error) {
      console.error('登录失败:', error)
      ElMessage.error(error.message || '登录失败')
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 退出登录
  const logout = async () => {
    try {
      await authApi.logout()
    } catch (error) {
      console.error('退出登录API调用失败:', error)
    } finally {
      // 无论API调用是否成功，都清除本地状态
      token.value = null
      user.value = null
      authUtils.clearAuthData()
      
      ElMessage.success('已退出登录')
    }
  }

  // 刷新用户信息
  const refreshUserInfo = async () => {
    try {
      const userInfo = await authApi.getCurrentUser()
      user.value = userInfo
      
      // 更新本地存储
      authUtils.saveAuthData(token.value, userInfo)
      
      return userInfo
    } catch (error) {
      console.error('刷新用户信息失败:', error)
      // 如果获取用户信息失败，可能是token无效
      await logout()
      throw error
    }
  }

  // 验证token有效性
  const validateAuth = async () => {
    if (!token.value) {
      return false
    }

    try {
      const userInfo = await authApi.getCurrentUser()
      user.value = userInfo
      return true
    } catch (error) {
      console.error('Token验证失败:', error)
      await logout()
      return false
    }
  }

  // 更新用户信息
  const updateProfile = async (profileData) => {
    try {
      isLoading.value = true
      
      const updatedUser = await authApi.updateProfile(profileData)
      user.value = updatedUser
      
      // 更新本地存储
      authUtils.saveAuthData(token.value, updatedUser)
      
      ElMessage.success('个人信息更新成功')
      return updatedUser
      
    } catch (error) {
      console.error('更新个人信息失败:', error)
      ElMessage.error(error.message || '更新失败')
      throw error
    } finally {
      isLoading.value = false
    }
  }

  // 检查认证状态并处理过期
  const checkAuthStatus = () => {
    if (!isLoggedIn.value) {
      return false
    }

    if (authUtils.isTokenExpired()) {
      ElMessage.warning('登录已过期，请重新登录')
      logout()
      return false
    }

    return true
  }

  return {
    // 状态
    user,
    token,
    isLoading,
    isInitialized,
    isDarkMode,
    
    // 计算属性
    isLoggedIn,
    userInfo,
    isAdmin,
    
    // 方法
    initAuth,
    initTheme,
    toggleTheme: toggleDarkMode,
    login,
    logout,
    refreshUserInfo,
    validateAuth,
    updateProfile,
    checkAuthStatus
  }
})
